package com.example.controller;

import com.example.pojo.User;

import com.example.service.UserService;
import com.example.vo.ApiResponse;
import com.example.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@Slf4j
public class LoginController {
    @Autowired
    private UserService userService;

    //展示登录页
    @GetMapping({"/","/login"})
    public String showLogin(){
        return "login";
    }

    //登录
    @PostMapping("/login")
    public String login(HttpSession session,
                        Model model,
                        @RequestParam String username,
                        @RequestParam String password){
        if (username!=null&&password!=null){
            User user=userService.login(username,password);
            if (user!=null){
                // 存储登录用户的用户信息
                session.setAttribute("user", user);
                return "redirect:index";
            }else {
                model.addAttribute("error", "用户名或密码错误！");
                model.addAttribute("username",username);
                model.addAttribute("password",password);
                return "login";
            }
        }else {
            model.addAttribute("error", "用户名或密码不能为空！");
            model.addAttribute("username",username);
            model.addAttribute("password",password);
            return "login";
        }
    }

}
